package com.easyexcell.easyexcellexample.utils.esayexcell.handler;


import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;

/**
 * 设置单元格格式
 *
 * @User c.c
 * @Since 2023/9/1
 * @Time 16:21
 * @Description
 */
@Slf4j
public class CustomCellWriteHandler implements CellWriteHandler {

  @Override
  public int order() {
    return 1000000;
  }

  @Override
  public void afterCellDispose(CellWriteHandlerContext context) {
    Cell cell = context.getCell();
    log.info("进入第" + cell.getRowIndex() + "行,第" + cell.getColumnIndex() + "列数据...");
    if (cell.getRowIndex() >= 2 && 9 == cell.getColumnIndex()) {
      // 含税总价 = 含税单价 * 采购数量 * 含税单价（元）
      // 以第3行数据为例：含税总价 = H3*F3 变为 = ROUNDDOWN(H3*F3,2)
      int actualCellRowNum = cell.getRowIndex() + 1;
      cell.setCellFormula("ROUNDDOWN(" + "H" + actualCellRowNum + "*F" + actualCellRowNum + ",2" + ")");
      log.info("第" + cell.getRowIndex() + "行,第" + cell.getColumnIndex() + "含税总价写入公式完成");
    }
    if (cell.getRowIndex() >= 2 && 10 == cell.getColumnIndex()) {
      // 未税单价 = 含税单价 / 1+税率
      // 以第3行数据为例：未税单价 = =H3/(1+I3/100)
      int actualCellRowNum = cell.getRowIndex() + 1;
      cell.setCellFormula("ROUNDDOWN(" + "H" + actualCellRowNum + "/" + "(1+" + "I" + actualCellRowNum + "/100),2" + ")");
      log.info("第" + cell.getRowIndex() + "行,第" + cell.getColumnIndex() + "未税单价写入公式完成");
    }
    if (cell.getRowIndex() >= 2 && 11 == cell.getColumnIndex()) {
      // 未税总价（元） = 未税单价 * 数量
      // 以第3行数据为例：未税单价 = =K3*F3
      int actualCellRowNum = cell.getRowIndex() + 1;
      cell.setCellFormula("ROUNDDOWN(" + "K" + actualCellRowNum + "*" + "F" + actualCellRowNum + ",2)");
      log.info("第" + cell.getRowIndex() + "行,第" + cell.getColumnIndex() + "未税单价写入公式完成");
    }
  }
}
